package com.itheima.udp1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer1 {

    public static void main(String[] args) throws Exception {

        //简单的UDP通信一发一收：服务端开发

        System.out.println("==========服务端启动==========");

        //1.创建接收端对象，绑定端口号
        DatagramSocket socket = new DatagramSocket(8080);

        //2.创建一个数据包对象负责接收数据
        byte[] bytes = new byte[1024 * 64];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);

        //3.调用接收方法，将数据接收到数据包对象的字节数组中去
        socket.receive(packet);

        //4.查看数据是否收到
        int len = packet.getLength();
        String data = new String(bytes, 0, len);
        System.out.println("服务端接收到了：" + data);

        //获取发送端的地址和端口号
        System.out.println("发送端的地址：" + packet.getAddress().getHostAddress());
        System.out.println("发送端的端口号：" + packet.getPort());

        //关闭
        socket.close();

    }
}
